﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.GData.Analytics;
using AnalyticsGadget.Models;

namespace AnalyticsGadget
{
    public static class StatisticsHelper
    {
        const string DataFeedUrl = "https://www.google.com/analytics/feeds/data";

        private static List<Profile> _profiles = null;
        
        public static List<Profile> Profiles
        {
            get
            {
                try
                {
                    if (_profiles == null)
                    {
                        List<Profile> profiles = new List<Profile>();

                        AnalyticsService client = CreateServiceProxy();
                        AccountQuery query = new AccountQuery();
                        AccountFeed accountFeed = client.Query(query);

                        foreach (AccountEntry entry in accountFeed.Entries)
                        {
                            Profile profile = new Profile() { ID = entry.ProfileId.Value, Name = entry.Title.Text };

                            profiles.Add(profile);
                        }

                        _profiles = profiles;
                    }

                    return _profiles;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        public static string[] Timespans
        {
            get 
            {
                List<string> list = new List<string>();

                foreach(Timespan time in Enum.GetValues(typeof(Timespan)))
                {
                    list.Add(time.ToString());
                }

                return list.ToArray();
            }
        }

        public static Profile DefaultProfile { get { return Profiles[0]; } }

        public static Report GetReport(ReportQuery query)
        {
            Report report = new Report();
            report.CurrentTimespan = query.Timespan;
            List<ReportData> dateItems = new List<ReportData>();

            report.CurrentProfileID = query.ProfileID;
           
            string dimensionQuery = string.Empty;
            string metricQuery = string.Empty;
            string sortyByQuery = string.Empty;

            foreach (DimensionType dimension in query.Dimensions)
            {
                if (dimensionQuery != string.Empty)
                {
                    dimensionQuery += ",";
                }

                dimensionQuery += "ga:" + dimension.ToString().ToLower();
            }

            metricQuery = "ga:" + query.Metric.ToString().ToLower();
            
            foreach (SortBy sortBy in query.SortyByList)
            {
                if (sortyByQuery != string.Empty)
                {
                    sortyByQuery += ",";
                }

                if (sortBy.Direction == SortDirection.Descending)
                {
                    sortyByQuery += "-";
                }

                sortyByQuery += "ga:" + sortBy.DataField;
            }

            DataQuery dataQuery = new DataQuery(DataFeedUrl);
            dataQuery.Ids = query.ProfileID;
            dataQuery.Metrics = metricQuery;
            dataQuery.Dimensions = dimensionQuery;
            dataQuery.Sort = sortyByQuery;

            if(query.MaxRecords > 0)
            {
                dataQuery.NumberToRetrieve = query.MaxRecords;
            }

            if (query.StartDate != null)
            {
                dataQuery.GAStartDate = query.StartDate.Value.ToString("yyyy-MM-dd");
            }

            if (query.StopDate != null)
            {
                dataQuery.GAEndDate = query.StopDate.Value.ToString("yyyy-MM-dd");
            }

            AnalyticsService client = CreateServiceProxy();
            DataFeed dataFeed = client.Query(dataQuery);

            foreach (DataEntry entry in dataFeed.Entries)
            {
                ReportData data = new ReportData();

                for (int i = 0; i < entry.Dimensions.Count; i++)
                {
                    string dimensionField = query.Dimensions[i].ToString();
                    string dimensionValue = entry.Dimensions[i].Value;

                    if(dimensionField.ToLower() == DimensionType.Date.ToString().ToLower())
                    {
                        dimensionValue = DateTime.ParseExact(dimensionValue, "yyyyMMdd", null).ToString("dd/MM-yyyy");
                    }

                    data.Add(dimensionField, dimensionValue);
                }

                //data.Add(query.Metric.ToString(), entry.Metrics[0].Value);

                
                data.Value = entry.Metrics[0].IntegerValue;

                dateItems.Add(data);
            }

            report.DataItems = dateItems;

            return report;         
        }
     
        #region Util

        private static Profile GetProfile(string profile)
        {
            var query = from p in Profiles
                        where p.ID == profile
                        select p;

            return query.SingleOrDefault();
        }
        
        private static AnalyticsService CreateServiceProxy()
        {
            string userName = System.Configuration.ConfigurationManager.AppSettings["AnalyticsGadget.Username"];
            string passWord = System.Configuration.ConfigurationManager.AppSettings["AnalyticsGadget.Password"];
            
            AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
            if (!string.IsNullOrEmpty(userName))
            {
                service.setUserCredentials(userName, passWord);
            }

            return service;
        }

        

        #endregion

    }
    
}
